#pragma once
#include<stdio.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<iostream>
#include<pthread.h>

class HttpSer{
  public:
  HttpSer(){
    listen_sockfd=-1;
  }
  ~HttpSer(){
    if(listen_sockfd>0){
      close(listen_sockfd);
    }
  }
  int init(){
    listen_sockfd= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(listen_sockfd<0){
      return -1;
    } 
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(2927);
    addr.sin_addr.s_addr=inet_addr("0.0.0.0");
  int  ret= bind(listen_sockfd,(struct sockaddr*)&addr,sizeof(addr));
    if(ret<0){
      return -2;
    }
    ret=listen(listen_sockfd,2);
    if(ret<0){
      return -3;
    }
    return 0;
  }
  void StartSer(){
    while(1){
      struct sockaddr_in addr;
      socklen_t peer_len=sizeof(addr);
      int new_sockfd=accept(listen_sockfd,(struct sockaddr*)&addr,&peer_len);
      if(new_sockfd<0){
        continue;
      }
      pthread_t tid;
      int* tmp=new int;
      *tmp=new_sockfd;
      int ret=   pthread_create(&tid,NULL,work_exp,(void*)tmp);
      if(ret<0){
        perror("pthread_create");
        close(new_sockfd);
        delete tmp;
      }
    }
  }
  static void* work_exp(void* arg){
    pthread_detach(pthread_self());
    int new_sockfd=*((int*)arg);
    delete (int*)arg;
    while(1){
      char buf[4096]={0};
      size_t r_size = recv(new_sockfd,buf,sizeof(buf)-1,0);
      if(r_size<0){
        continue;
      }else if(r_size==0){  
        close(new_sockfd); 
        break;
      }

      std::cout<<"**************begin*************"<<std::endl;
      std::cout<<buf;
      std::cout<<"**************end*************"<<std::endl;
  
      std::string content="hello";
      std::string line="HTTP/1.1 302 OK\r\n";
      std::string body="Content-Type:text/html\r\n";
      
      body+="Set-Cookie: Linuxxy\r\n";
      body+="Custom-Header: custom value\r\n";
      body+="Content-Length:5\r\n";
      body+="Location: https://www.baidu.com/\r\n\r\n";

      send(new_sockfd,line.c_str(),line.size(),0);
      send(new_sockfd,body.c_str(),body.size(),0);
      send(new_sockfd,content.c_str(),content.size(),0);
    }
    
      

  }
  private:
  int listen_sockfd;

};

